package com.humble.vichatbackend.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.humble.vichatbackend.common.*;
import com.humble.vichatbackend.constant.UserConstant;
import com.humble.vichatbackend.exception.BusinessException;
import com.humble.vichatbackend.model.domain.Team;
import com.humble.vichatbackend.model.domain.UserTeam;
import com.humble.vichatbackend.model.enums.ErrorCode;
import com.humble.vichatbackend.model.vo.UserTeamVO;
import com.humble.vichatbackend.model.vo.UserVO;
import com.humble.vichatbackend.service.TeamService;
import com.humble.vichatbackend.service.UserService;
import com.humble.vichatbackend.service.UserTeamService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;



import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/team")
@Tag(name="队伍接口列表")
public class TeamController {
    @Resource
    TeamService teamService;

    @Resource
    UserService userService;

    @Resource
    UserTeamService userTeamService;

    @PostMapping("/add")
    @Operation(description="新建队伍接口")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) {
        if(teamAddRequest==null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        UserVO currentUser = userService.getCurrentUser(request);
        return BaseResponse.success(teamService.addTeam(teamAddRequest,currentUser));
    }

    @PostMapping("/update")
    @Operation(description="修改队伍接口")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest, HttpServletRequest request) {
        if (teamUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO currentUser = userService.getCurrentUser(request);
        boolean result = teamService.updateTeam(teamUpdateRequest, currentUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新失败");
        }
        return BaseResponse.success(true);
    }

    @GetMapping("/get")
    @Operation(description="通过id获取队伍接口")
    public BaseResponse<Team> getTeamById(Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById(id);
        if (team == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return BaseResponse.success(team);
    }

    @GetMapping("/list")
    @Operation(description="查询队伍接口")
    public BaseResponse<List<UserTeamVO>> listTeams(@RequestBody TeamQueryRequest teamQueryRequest, HttpServletRequest request) {
        if (teamQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO currentUser = userService.getCurrentUser(request);
        boolean isAdmin = currentUser.getUserRole()== UserConstant.ADMIN_ROLE;
        return BaseResponse.success(teamService.listTeams(teamQueryRequest, isAdmin,currentUser.getId()));
    }

    // todo 查询分页
    @GetMapping("/list/page")
    @Operation(description="分页查询队伍接口")
    public BaseResponse<Page<Team>> listTeamsByPage(@RequestBody TeamQueryRequest teamQueryRequest,HttpServletRequest request) {
        if (teamQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO currentUser = userService.getCurrentUser(request);
        boolean isAdmin = currentUser.getUserRole()== UserConstant.ADMIN_ROLE;

        Page<Team> resultPage = teamService.listTeamsByPage(teamQueryRequest, isAdmin,currentUser.getId());

        // Team team = new Team();
        // BeanUtils.copyProperties(teamQueryRequest, team);
        // Page<Team> page = new Page<>(teamQueryRequest.getPageNum(), teamQueryRequest.getPageSize());
        // QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        // Page<Team> resultPage = teamService.page(page, queryWrapper);

        return BaseResponse.success(resultPage);
    }

    @PostMapping("/join")
    @Operation(description="加入队伍接口")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request) {
        if (teamJoinRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO loginUser = userService.getCurrentUser(request);
        boolean result = teamService.joinTeam(teamJoinRequest, loginUser);
        return BaseResponse.success(result);
    }

    @PostMapping("/quit")
    @Operation(description="退出队伍接口")
    public BaseResponse<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request) {
        if (teamQuitRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO loginUser = userService.getCurrentUser(request);
        boolean result = teamService.quitTeam(teamQuitRequest, loginUser);
        return BaseResponse.success(result);
    }

    @PostMapping("/delete")
    @Operation(description="删除队伍接口")
    public BaseResponse<Boolean> deleteTeam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        UserVO loginUser = userService.getCurrentUser(request);
        boolean result = teamService.deleteTeam(id, loginUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除失败");
        }
        return BaseResponse.success(true);
    }


    /**
     * 获取我创建的队伍
     *
     * @param teamQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/my/create")
    @Operation(description="获取自己创建的队伍接口")
    public BaseResponse<List<UserTeamVO>> listMyCreateTeams(@RequestBody TeamQueryRequest teamQueryRequest, HttpServletRequest request) {
        if (teamQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO loginUser = userService.getCurrentUser(request);
        teamQueryRequest.setUserId(loginUser.getId());
        List<UserTeamVO> teamList = teamService.listTeams(teamQueryRequest, true,loginUser.getId());
        return BaseResponse.success(teamList);
    }


    /**
     * 获取我加入的队伍
     *
     * @param teamQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/my/join")
    @Operation(description="获取自己加入的队伍接口")
    public BaseResponse<List<UserTeamVO>> listMyJoinTeams(@RequestBody TeamQueryRequest teamQueryRequest, HttpServletRequest request) {
        if (teamQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO loginUser = userService.getCurrentUser(request);
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", loginUser.getId());
        List<UserTeam> userTeamList = userTeamService.list(queryWrapper);
        // 取出不重复的队伍 id,防止个人重复加入出现重复队伍id问题；
        // teamId userId
        // 1, 2
        // 1, 3
        // 2, 3
        // result
        // 1 => 2, 3
        // 2 => 3
        Map<Long, List<UserTeam>> listMap = userTeamList.stream()
                .collect(Collectors.groupingBy(UserTeam::getTeamId));
        List<Long> idList = new ArrayList<>(listMap.keySet());
        teamQueryRequest.setIdList(idList);
        List<UserTeamVO> teamList = teamService.listTeams(teamQueryRequest, true,loginUser.getId());
        return BaseResponse.success(teamList);
    }
}
